# Echo server origran
import socket
#import numpy as np
import sys
import Queue
from threading import Thread
import time
import select
import traceback

import ttrConst 
reload(ttrConst)
from ttrConst import *

import ttrServerProc
reload(ttrServerProc)
from ttrServerProc import client, clientProcess

import pdb

class master:
    def __init__(self, server):
        self.s = server
        self.main_state = server_main_state['OK']
        self.ClientSet = []
        self.process = Thread(target=clientProcess , args=(self.ClientSet, self,))
        self.process.setDaemon(True)
        self.process.start()
        self.run()

    def run(self):
        #self.s.setblocking(0)
        #self.s.settimeout(5)
        print 'listening ...'
        
        while self.main_state == server_main_state['OK']:
            self.s.listen(TOTAL_CLIENTS) # blocking
            
            if self.main_state == server_main_state['OK']:
                conn, addr = self.s.accept()
                print 'Connected by ', conn
                # pass the conn and addr to a new client-server-thread
                # the client server shall collect input from client and pass it to main server via client 
                self.ClientSet.append(client(conn, addr, in_q=Queue.Queue(), out_q=Queue.Queue()))
                    
        else:
            self.s.close()
            print 'main stop'
        
    def kill_main(self):
        self.main_state = server_main_state['stop']
        # psuedo client to wake up listen
        psuedo = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        psuedo_ip = socket.gethostbyname_ex(socket.gethostname())[0]
        psuedo.connect((psuedo_ip, GAME_PORT)) #make up socket lieten
        psuedo.close()
            
        
if __name__ == '__main__':
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind( ('', GAME_PORT) )
        
        c = master(s)
        
    except:
        traceback.print_exc() 
        del s
    


